package com.xieyong.mywebsite.interceptors;

import cn.hutool.core.util.StrUtil;
import com.xieyong.mywebsite.exception.MyCustomizeException;
import com.xieyong.mywebsite.util.RedisUtil;
import com.xieyong.mywebsite.util.ThreadLocalUtil;
import com.xieyong.mywebsite.util.TokenUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class JWTInterceptor implements HandlerInterceptor {

    public JWTInterceptor(){
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        System.out.println("----------------------------拦截路径: "+ request.getMethod() + "--" + request.getRequestURI() + "-------------------------------");  // 查看实际路径
//        拿到token
        String token = request.getHeader("Authorization");
        if(StrUtil.isBlank(token)){
            token = request.getHeader("token");
            if(StrUtil.isBlank(token)){
                token = request.getParameter("token");
            }
        }
//        验证token
        try {
//            从redis中获取相同的token
            String redisToken = RedisUtil.get(token);
            if(StrUtil.isBlank(redisToken)){
                throw new MyCustomizeException("401", "token验证失败");
            } else {
//              如果redis中有token，说明已经登录过了,查看是否写入信息
                if (ThreadLocalUtil.get() == null) {
                    Map<String, Object> claims = TokenUtil.parseToken(token);
//                  将业务数据存储到threadlocal
                    ThreadLocalUtil.set(claims);
                }
            }
        } catch (Exception e) {
            System.out.println(e.getMessage());
            response.setStatus(401);
            throw new MyCustomizeException("401", "token验证失败");
        }
        return true;
    }

//    在请求完成后将threadlocal清楚防止内存泄漏
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex){
        ThreadLocalUtil.remove();
    }
}
